package com.zd.springcloud.tccaction.impl;

import com.zd.springcloud.domain.Order;
import com.zd.springcloud.enums.OrderStatus;
import com.zd.springcloud.mapper.OrderMapper;
import com.zd.springcloud.tccaction.OrderAction;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderActionImpl implements OrderAction{

    @Autowired(required = false)
    OrderMapper orderMapper;

    @Override
    public void addOrder(BusinessActionContext businessActionContext, Order order) {


        String xid = businessActionContext.getXid();
        //解决幂等问题
        if (orderMapper.existsTryLog(xid) > 0){
            return;
        }

        //解决悬挂问题 没有执行过try 或者 commit就执行 try
        if(orderMapper.existsCommitLog(xid)>0 || orderMapper.existsRollbackLog(xid)>0){
            return;
        }


        orderMapper.addOrder(order);
        //添加订单后添加日志
        orderMapper.insertTryLog(xid);
    }

    @Override
    public void commit(BusinessActionContext businessActionContext) {
        String xid = businessActionContext.getXid();
        //解决幂等问题
        if (orderMapper.existsCommitLog(xid) > 0){
            return;
        }
        //解决空提交的问题，一般很少发生
        if(orderMapper.existsTryLog(xid)==0){
            return;
        }

        Order order = businessActionContext.getActionContext("order",Order.class);
        //修改订单状态由新建到 成功
        order.setStatus(OrderStatus.SUCCESS.name());
        orderMapper.commit(order);


        //提交成功后添加日志
        orderMapper.insertCommitLog(xid);
    }

    @Override
    public void rollback(BusinessActionContext businessActionContext) {
        String xid = businessActionContext.getXid();

        //解决幂等问题
        if (orderMapper.existsRollbackLog(xid) > 0){
            return;
        }
        //解决空回滚的问题
        if(orderMapper.existsTryLog(xid)==0){
            return;
        }

        Order order = businessActionContext.getActionContext("order",Order.class);
        orderMapper.rollback(order);

        //回滚后添加日志
        orderMapper.insertRollbackLog(xid);
    }
}
